namespace NBody.Analysis
{
    using System;
    using DataFile;
    
    public class GenericBin : Bin
    {
        Function f;
        Function bin;
        
        public Function F
        {
            set{ f = value; }
        }
        
        public Function Bin
        {
            set { bin = value; }
        }
        
        public override void Analyse(NBodySystem s)
        {
            Console.Error.WriteLine("  Binning with normal spacing");
            
            // find max, min
            double min = bin(s[0]);
            double max = min;
            foreach (Particle p in s)
            {
                double test = bin(p);
                if (test > max)
                    max = test;
                if (test < min)
                    min = test;
            }
            max += 1e-10;
            Console.Error.WriteLine("  Min = {0:f6}\n  Max = {1:f6}", min, max);
            
            double delta = (max - min) / (double)n;
            data = new Table(n, 2, "Bin, Binned quantity");
            data.Clear();
            for (int i = 0; i < n; i++)
                data[i, 0] = min + 0.5 * delta + i * delta;

            foreach (Particle p in s)
            {
                double x = bin(p);
                int pos = (int)((x - min) / delta);
                data[pos, 1] += f(p);
            }
            
            for (int i = 0; i  < data.Length; i++)
                data[i, 1] /= delta;
        }
    }
}   		
